package com.kll.tv.views

import android.content.ContentResolver
import android.content.ContentUris
import android.content.Intent
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.os.FileUtils
import android.provider.DocumentsContract
import android.provider.MediaStore
import android.provider.OpenableColumns
import android.view.View
import androidx.annotation.RequiresApi
import com.kll.carolinehmibiz.OperationManager
import com.kll.carolinehmibiz.model.AccountModel
import com.kll.carolinehmibiz.model.OperateListener
import com.kll.carolinehmibiz.net.bean.RefreshTokenResponse
import com.kll.carolinehmibiz.net.bean.UploadFileResponse
import com.kll.carolinehmibiz.presentation.listener.PersonalAvatarProtocol
import com.kll.carolinehmibiz.presentation.presenter.PersonalAvatarPresenter
import com.kll.tv.base.views.BaseActivity
import com.kll.tv.databinding.ActivityPersonalAvatarBinding
import com.kll.tv.utils.AppToast
import com.kll.carolinehmibiz.base.utils.L
import com.kll.tv.utils.PopWindow
import com.kll.tv.views.adapter.PersonalAvatarPopAdapter
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import kotlin.math.roundToInt

/**
 * 个人头像页
 */
class PersonalAvatarActivity: BaseActivity<PersonalAvatarPresenter>(), PersonalAvatarProtocol.IView {
    private lateinit var binding: ActivityPersonalAvatarBinding
    private var avatarAbsolutePath = ""
    private var popWindow: PopWindow? = null
    private var personalAvatarPopAdapter: PersonalAvatarPopAdapter? = null
    companion object {
        const val REQUESTCODE_CHOOSE_IMAGE = 1
    }

    override fun initViewBinding(): View {
        binding = ActivityPersonalAvatarBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun createPresenter(): PersonalAvatarPresenter {
        return PersonalAvatarPresenter(this, this)
    }

    override fun init() {

        initListener()
    }

    private fun initListener() {
        binding.ivMore.setOnClickListener {

        }

        binding.ivCover.setOnClickListener {
            chooseImage()
        }

        binding.ivBack.setOnClickListener { finish() }
        binding.ivBackCircular.setOnClickListener { finish() }
    }

    private fun chooseImage(){
        val intent = Intent(Intent.ACTION_PICK, null)
        if (Build.VERSION.SDK_INT >= 28) {
            intent.setAction(Intent.ACTION_PICK)
        } else {
            intent.setAction(Intent.ACTION_OPEN_DOCUMENT)
        }
        startActivityForResult(intent, REQUESTCODE_CHOOSE_IMAGE)
    }

    override fun uploadHeadImgSuccessed(data: UploadFileResponse) {

    }

    override fun uploadHeadImgFailed(code: Int, message: String) {
        AppToast.show(message, 2000)
        if (code == 102) {
            // token过期 刷新token
            OperationManager.getInstancce().refreshToken(object : OperateListener {
                override fun onSuccess(state: Int, obj: Any?) {
                    var data = obj as RefreshTokenResponse
                    AccountModel.getInstance(baseContext).updateUserToken(data.token)
                }

                override fun onFail(code: Int, message: String) {
                    AppToast.show(message, 2000)
                    if (code == 101) {
                        loginAgain()
                    }
                }

            })
        }
        if (code == 101) {
            loginAgain()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if(requestCode == REQUESTCODE_CHOOSE_IMAGE) {
            var uri = data?.data

            if(uri != null) {
                avatarAbsolutePath = getFileAbsolutePath(uri) ?: ""

                // 上传
                L.d("TAG", "onActivityResult: ${avatarAbsolutePath}")
                mPresenter.uploadHeadImg(File(avatarAbsolutePath))

                // SharedPreferenceUtils.getInstance(this).saveValueToSharePerference("data", Gson().toJson(adapter.datas))
            }

        }
    }

    fun getFileAbsolutePath(imageUri: Uri): String? {
        if (imageUri == null) {
            return null
        }

        // 4.4以下
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
//            return getRealFilePath(context, imageUri);
            return null
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.Q && DocumentsContract.isDocumentUri(this, imageUri)) {
            if (isExternalStorageDocument(imageUri)) {
                var docId = DocumentsContract.getDocumentId(imageUri)
                var split = docId.split(":")
                var type = split[0]
                if ("primary" == type.lowercase()) {
                    return "${Environment.getExternalStorageDirectory()}/${split[1]}"
                }
            } else if (isDownloadsDocument(imageUri)) {
                var id = DocumentsContract.getDocumentId(imageUri);
                var contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), id.toLong());
                return getDataColumn( contentUri, null, null);
            } else if (isMediaDocument(imageUri)) {
                var docId = DocumentsContract.getDocumentId(imageUri);
                var split = docId.split(":");
                var type = split[0];
                var contentUri: Uri? = null
                if ("image" == type) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video" == type) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio" == type) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                var selection = MediaStore.Images.Media._ID + "=?";
                var selectionArgs = arrayOf(split[1])
                return getDataColumn(contentUri, selection, selectionArgs);
            }
        }

        // MediaStore (and general)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
            return uriToFileApiQ(imageUri);
        }
        else if ("content" == imageUri.scheme?.lowercase()) {
            // Return the remote address
            if (isGooglePhotosUri(imageUri)) {
                return imageUri.lastPathSegment;
            }
            return getDataColumn( imageUri, null, null);
        }
        // File
        else if ("file" == imageUri.scheme?.lowercase()) {
            return imageUri.path;
        }
        return null
    }

    private fun isExternalStorageDocument(uri: Uri): Boolean {
        return "com.android.externalstorage.documents" == uri.authority
    }

    private fun isDownloadsDocument(uri: Uri) :Boolean {
        return "com.android.providers.downloads.documents" == uri.authority
    }

    private fun getDataColumn(uri: Uri?, selection: String?, selectionArgs: Array<String>?): String? {
        var cursor: Cursor? = null
        var column = MediaStore.Images.Media.DATA
        var projection = arrayOf(column);
        try {
            cursor = getContentResolver().query(uri!!, projection, selection, selectionArgs, null)!!;
            if (cursor != null && cursor.moveToFirst()) {
                var index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            cursor?.close()
        }
        return null
    }

    private fun isMediaDocument(uri: Uri): Boolean {
        return "com.android.providers.media.documents" == uri.authority
    }

    @RequiresApi(Build.VERSION_CODES.Q)
    private fun uriToFileApiQ(uri: Uri?): String? {
        var file: File? = null;
        //android10以上转换
        if (uri!!.scheme.equals(ContentResolver.SCHEME_FILE)) {
            file = File(uri.path);
        } else if (uri!!.scheme.equals(ContentResolver.SCHEME_CONTENT)) {
            //把文件复制到沙盒目录
//            var contentResolver = contentResolver;
            var cursor = contentResolver.query(uri!!, null, null, null, null);
            if (cursor!!.moveToFirst()) {
                var displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                try {
                    var inputStream = contentResolver.openInputStream(uri);
                    var cache = File(externalCacheDir!!.absolutePath, "${((Math.random() + 1) * 1000).roundToInt()}${displayName}")
                    var fos = FileOutputStream(cache)
                    FileUtils.copy(inputStream!!, fos)
                    file = cache;
                    fos.close();
                    inputStream?.close();
                } catch (e: IOException) {
                    e.printStackTrace();
                }
            }
        }
        return file?.absolutePath;
    }

    private fun isGooglePhotosUri(uri: Uri): Boolean {

        return "com.google.android.apps.photos.content" == uri.authority
    }

}